import numpy as np
import matplotlib.pyplot as plt
import struct

#y(n) = (x(n)+x(n-1)+x(n-2)+x(n-3))/4
class Digitfilter:
    def __init__(self):
        self.xn = [0,0,0]
        pass

    def filter(self,x):
        y =  (x + self.xn[0] + self.xn[1] + self.xn[2])/4
        self.xn[2] = self.xn[1]
        self.xn[1] = self.xn[0]
        self.xn[0] = x
        print(x,y, self.xn[0], self.xn[1], self.xn[2])
        return y

if __name__ =='__main__':
    fp = open("D:/wuhui/testcode/SmartHealth-master/DATA/mitdb/102.dat","rb")
    fp_out = open("D:/wuhui/testcode/SmartHealth-master/DATA/mitdb/102_out.dat","wb")
    diff = Digitfilter()
    for i in range(0,2500):
        x = struct.unpack('h',fp.read(2))
        y = diff.filter(x[0])
        fp_out.write(struct.pack('h',int(y)))
    fp.close()
    fp_out.close()


    ecg0 = np.fromfile("D:/wuhui/testcode/SmartHealth-master/DATA/mitdb/102.dat",dtype=np.short)
    ecg1 = np.fromfile("D:/wuhui/testcode/SmartHealth-master/DATA/mitdb/102_out.dat",dtype=np.short)
    plt.subplot(2,1,1)
    plt.plot(ecg0[0:500])
    plt.subplot(2,1,2)
    plt.plot(ecg1[0:500])
    plt.show()